package org.brownflat.lighthouse.monitoring.monitor;

import org.apache.log4j.Logger;
import org.brownflat.lighthouse.monitoring.action.Action;
import org.brownflat.lighthouse.monitoring.ci.Monitorable;
import org.brownflat.lighthouse.monitoring.device.Device;

public class AnyBrokenBuildTask implements LighthouseTask {

    private Monitorable monitorable;
    private Action whenBroken;
    private Action whenNotBroken;
    private Action whenResetNeeded;
    private boolean broken = false;
    private String name = null;
    private Device device;
    private static final Logger LOG = Logger.getLogger(AnyBrokenBuildTask.class);

    public AnyBrokenBuildTask(String name, Monitorable monitorable, Device device, Action reset, Action broken, Action notBroken) {
        this.monitorable = monitorable;
        this.device = device;
        this.whenBroken = broken;
        this.whenNotBroken = notBroken;
        this.whenResetNeeded = reset;
        this.name = name;
    }

    @Override
    public void run() {
        LOG.debug("Checking for any broken build");
        if (monitorable.hasAnyBrokenBuilds()) {
            if (!broken) {
                execute(whenResetNeeded);
            }

            broken = true;
            execute(whenBroken);
            LOG.error("BROKEN BUILD DETECTED.");
        } else {
            if (broken) {
                LOG.error("BROKEN BUILD FIXED.");
                execute(whenResetNeeded);
            }
            LOG.info("BUILDS OK.");
            broken = false;
            execute(whenNotBroken);
        }
    }

    @SuppressWarnings("unchecked")
    private void execute(Action action) {
        LOG.debug("Action executing: " + action.getActionDescription());
        device.execute(action);
    }

    public Monitorable getMonitorable() {
        return monitorable;
    }

    @Override
    public String getName() {
        return name;
    }
}
